import 'dart:ui';

import 'package:buttons_tabbar/buttons_tabbar.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:date_format/date_format.dart';
import 'package:fbutton/fbutton.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xm_app/common/common.dart';
import 'package:xm_app/common/logger/LoggerUtil.dart';
import 'package:xm_app/common/ui/AppTheme.dart';
import 'package:xm_app/common/ui/ui_adapter.dart';
import 'package:xm_app/common/ui/ui_image.dart';
import 'package:xm_app/model/HomeData.dart';
import 'package:xm_app/model/VodDetails.dart';
import 'package:xm_app/page/vod/VodDetailController.dart';
import 'package:xm_app/r.dart';
import 'package:xm_app/routes/AppRoutes.dart';
import 'package:xm_app/widget/CommonGrid.dart';
import 'package:xm_app/widget/CommonText.dart';
import 'package:xm_app/widget/StarRating.dart';
import 'package:xm_app/widget/toggle_rotate.dart';

import '../../widget/PlayListWidget.dart';

// ignore: must_be_immutable
class VodDetailPage extends StatelessWidget {
  VodDetailController controller;
  @override
  Widget build(BuildContext context) {
    return GetBuilder<VodDetailController>(
      init: VodDetailController(),
      tag: Get.parameters["id"],
      builder: (c) {
        // logDebug("VodDetailPage GetBuilder");
        controller = c;
        return Scaffold(
          body: NotificationListener(
            onNotification: (scrollNotification) {
              if (scrollNotification is ScrollUpdateNotification) {
                if (scrollNotification.metrics.axis == Axis.vertical) {
                  controller.onScroll(scrollNotification.metrics.pixels);
                  // logDebug("scrollNotification.metrics.pixels : ${scrollNotification.metrics.pixels}");
                }
              }
              return false;
            },
            child: Stack(
              children: [
                controller.obx((_) {
                  // logDebug("VodDetailPage controller.obx");
                  return SingleChildScrollView(
                    child: Stack(
                      children: [
                        _buildBg(),
                        _buildContent(),
                      ],
                    ),
                  );
                }),
                Obx(() => _buildAppBar()),
              ],
            ),
          ),
        );
      },
    );
  }

  _buildAppBar() {
    return Container(
      color: AppTheme.pinkColor.withOpacity(controller.appBarAlpha.value),
      height: 56 + Get.mediaQuery.padding.top,
      child: Padding(
        padding: EdgeInsets.only(top: Get.mediaQuery.padding.top),
        child: Stack(
          children: [
            Row(
              children: [
                Center(
                  child: IconButton(
                      icon: Icon(
                        Icons.arrow_back_ios,
                        color: Colors.white,
                      ),
                      onPressed: () => Get.back()),
                ),
              ],
            ),
            if (controller.appBarAlpha.value > 0.5)
              Positioned.fill(
                  child: Center(
                child: CommonText(
                  controller.vodDetail.value.vod.vodName ?? "",
                  txtSize: getSp(16),
                  txtColor: Colors.white,
                ),
              ))
          ],
        ),
      ),
    );
  }

  _buildContent() {
    return Container(
      constraints: BoxConstraints(minHeight: Get.height - getHeight(160)),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(15),
            topRight: Radius.circular(15),
          )),
      margin: EdgeInsets.only(top: getHeight(160)),
      padding: EdgeInsets.only(left: 15, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildContentHeader(),
          _buildPlayBtn(),
          Container(
            child: CommonText(
              "剧情介绍",
              txtColor: AppTheme.iconYellow,
              txtWeight: FontWeight.w700,
              txtSize: getSp(16),
            ),
          ),
          SizedBox(height: getHeight(5)),
          ValueBuilder<CrossFadeState>(
            initialValue: CrossFadeState.showFirst,
            builder: (value, updateFn) {
              return Column(
                children: [
                  AnimatedCrossFade(
                    duration: Duration(microseconds: 500),
                    crossFadeState: value,
                    firstChild: CommonText(
                      "${controller.vodDetail.value.vod.vodContent ?? ""}",
                      maxLine: 2,
                      overflow: TextOverflow.fade,
                      txtColor: AppTheme.defaultTxtGrey,
                    ),
                    secondChild: Container(
                      child: CommonText(
                        "${controller.vodDetail.value.vod.vodContent ?? ""}",
                        txtColor: AppTheme.defaultTxtGrey,
                      ),
                    ),
                  ),
                  ToggleRotate(
                    onTap: () {
                      updateFn(value == CrossFadeState.showFirst ? CrossFadeState.showSecond : CrossFadeState.showFirst);
                    },
                    durationMs: 500,
                    child: Container(
                      child: Icon(
                        Icons.keyboard_arrow_down,
                        // size: getSp(20),
                        color: AppTheme.defaultIconGrey,
                      ),
                      padding: EdgeInsets.only(left: 5, right: 5),
                      // alignment: Alignment.topCenter,
                    ),
                  )
                ],
              );
            },
          ),
          SizedBox(height: getHeight(10)),
          PlayListWidget(
              vod: controller.vodDetail.value.vod,
              itemOnTap: (fromIndex, index) {
                toPlay(vod: controller.vodDetail.value.vod, index: index, fromIndex: fromIndex);
              }),
          SizedBox(height: getHeight(10)),
          _buildReList(name: "猜你喜欢", dataList: controller.vodDetail.value.rand),
          SizedBox(height: getHeight(10)),
          _buildReList(name: "相关推荐", dataList: controller.vodDetail.value.relate),
          SizedBox(height: getHeight(25)),
        ],
      ),
    );
  }

  _buildContentHeader() {
    return Container(
      height: getHeight(100),
      child: OverflowBox(
        maxHeight: getHeight(180),
        alignment: Alignment.bottomLeft,
        child: Row(
          children: [
            Container(
              height: getHeight(170),
              width: 257 / 360 * getHeight(170),
              child: buildNetImage(controller.vodDetail.value.vod.vodPic),
            ),
            Expanded(
              child: Container(
                padding: EdgeInsets.only(left: 10, top: 3),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      constraints: BoxConstraints(minHeight: getHeight(45)),
                      alignment: Alignment.centerLeft,
                      child: CommonText(
                        controller.vodDetail.value.vod.vodName,
                        txtColor: AppTheme.paper,
                        txtSize: getSp(16),
                        maxLine: 2,
                      ),
                    ),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        CommonText(
                          "${controller.vodDetail.value.vod.vodScore.toStringAsFixed(1) ?? ""}",
                          txtColor: AppTheme.iconYellow,
                          txtSize: getSp(13),
                        ),
                        SizedBox(width: getWidth(5)),
                        StarRating(maxRating: 10, rating: controller.vodDetail.value.vod.vodScore.toDouble(), starCount: 5, size: getSp(16))
                      ],
                    ),
                    SizedBox(
                      height: getHeight(35),
                    ),
                    Row(
                      children: [
                        CommonText(
                          "${controller.vodDetail.value.vod.vodYear ?? ""}",
                          txtSize: getSp(13),
                        ),
                        Container(
                          color: AppTheme.defaultTxtGrey,
                          height: 10,
                          width: 1,
                          margin: EdgeInsets.only(right: 5, left: 5),
                        ),
                        CommonText(
                          "${controller.vodDetail.value.vod.vodArea ?? ""}",
                          txtSize: getSp(13),
                        ),
                        Container(
                          color: AppTheme.defaultTxtGrey,
                          height: 10,
                          width: 1,
                          margin: EdgeInsets.only(right: 5, left: 5),
                        ),
                        CommonText(
                          "${controller.vodDetail.value.vod.vodClass.typeName ?? ""}",
                          txtSize: getSp(13),
                        ),
                      ],
                    ),
                    Row(
                      children: [
                        CommonText(
                          "状态：",
                          txtColor: AppTheme.defaultTxtGrey,
                          txtSize: getSp(13),
                        ),
                        CommonText(
                          "${controller.vodDetail.value.vod.vodRemarks ?? ""}",
                          txtColor: Colors.red,
                          txtSize: getSp(13),
                        ),
                        CommonText(
                          " / ",
                          txtColor: AppTheme.defaultTxtGrey,
                          txtSize: getSp(10),
                        ),
                        CommonText(
                          Commons.getVodTime(1611160794),
                          txtColor: AppTheme.defaultTxtGrey,
                          txtSize: getSp(13),
                        ),
                      ],
                    ),
                    Row(
                      children: [
                        CommonText(
                          "主演：",
                          txtColor: AppTheme.defaultTxtGrey,
                          txtSize: getSp(13),
                        ),
                        Expanded(
                            child: CommonText.singleLine(
                          "${controller.vodDetail.value.vod.vodActor ?? ""}",
                          txtSize: getSp(13),
                        ))
                      ],
                    ),
                    Row(
                      children: [
                        CommonText(
                          "导演：",
                          txtColor: AppTheme.defaultTxtGrey,
                          txtSize: getSp(13),
                        ),
                        CommonText(
                          "${controller.vodDetail.value.vod.vodDirector ?? ""}",
                          txtSize: getSp(13),
                        )
                      ],
                    )
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  _buildPlayBtn() {
    return Container(
      padding: EdgeInsets.only(top: 5),
      alignment: Alignment.center,
      child: FButton(
        onPressed: () {
          logDebug("vod ${controller.vodDetail.value.vod}");
          toPlay(vod: controller.vodDetail.value.vod, index: 0, fromIndex: 0);
        },
        image: Icon(
          Icons.play_arrow_sharp,
          color: Colors.white,
          size: getSp(20),
        ),
        alignment: Alignment.center,
        clickEffect: true,
        width: getWidth(200),
        height: getHeight(35),
        text: "立即播放",
        style: TextStyle(color: Colors.white, fontSize: getSp(13)),
        color: AppTheme.iconYellow,
        corner: FCorner.all(20),
      ),
    );
  }

  _buildBg() {
    return Stack(
      children: [
        Container(
          width: Get.width,
          height: Get.height / 2,
          child: CachedNetworkImage(
            imageUrl: controller.vodDetail.value.vod.vodPic,
            fit: BoxFit.cover,
          ),
        ),
        BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 90, sigmaY: 90),
          child: Container(
            color: Colors.black.withOpacity(0.3),
            width: Get.width,
            height: Get.height / 2,
          ),
        )
      ],
    );
  }

  _buildReList({String name, List<HomeDataItem> dataList}) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        Padding(
          padding: EdgeInsets.only(bottom: getHeight(10)),
          child: CommonText(
            name,
            txtWeight: FontWeight.w700,
            txtSize: getSp(14),
          ),
        ),
        SizedBox(
          height: 120,
          child: ListView.separated(
              scrollDirection: Axis.horizontal,
              itemBuilder: (BuildContext context, int index) {
                final item = dataList[index];
                return GestureDetector(
                  onTap: () {
                    logDebug("onTap ${item.vodName}");
                    toVodDetailPage(id: item.vodID);
                  },
                  child: SizedBox(
                    height: 120,
                    width: 130,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Expanded(
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(4),
                            child: Stack(
                              children: [
                                buildItemImage(item.vodPic),
                                buildUpdateText(item.vodRemarks),
                              ],
                            ),
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.all(5),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                item.vodName,
                                style: TextStyle(fontSize: getSp(12)),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                              Text(
                                item.vodActor,
                                style: TextStyle(fontSize: getSp(11)),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ],
                          ),
                        )
                      ],
                    ),
                  ),
                );
              },
              separatorBuilder: (BuildContext context, int index) {
                return SizedBox(
                  width: 5,
                );
              },
              itemCount: controller.vodDetail.value.rand.length),
        )
      ],
    );
  }
}
